package com.cus.tom.transfer.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DB_NAME = "trans.db";

    private static final int VERSION = 1;

    private final String CREATE_SEND = "CREATE TABLE IF NOT EXISTS send (id integer primary key autoincrement,path text, type integer, time integer, flag text)";
    private final String CREATE_RECV = "CREATE TABLE IF NOT EXISTS recv (id integer primary key autoincrement,path text, type integer, time integer, flag text)";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_SEND);
        db.execSQL(CREATE_RECV);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    private void addAvatar2Doc(SQLiteDatabase db) {
        if (isColumnExist(db, "doc2", "avatar")) {
            return;
        }
        try {
            db.execSQL("ALTER TABLE doc2 ADD COLUMN avatar text");
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private boolean isColumnExist(SQLiteDatabase db, String table, String column) {
        Cursor cursor = null;
        try {
            String sql = "select " + column + " from " + table + " limit 0,1";
            cursor = db.rawQuery(sql, null);
            return true;
        } catch (Throwable e) {
            return false;
        } finally {
            close(cursor);
        }
    }

    private void close(Cursor c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (Throwable e) {

        }
    }
}
